﻿#!/usr/bin/env python3
# -*-coding: UTF-8 -*-
import sys
import logging
import traceback
from pathlib import Path
from Clover.CloverEngine import CloverEngine
from CloverConst.CloverEnvironmentType import CloverEnvironmentType
from CloverWindow.MainApplication import CloverApplication


class CloverEnvironment:
	ENVIRONMENT_TYPE = 'None'
	BASE_PATH = Path(__file__)
	RESOURCES_PATH = Path(__file__)
	LOG_PATH = Path(__file__)


engine = CloverEngine()
app = CloverApplication(sys.argv)


def setup_environment():
	if getattr(sys, 'frozen', False):
		CloverEnvironment.ENVIRONMENT_TYPE = CloverEnvironmentType.RELEASE
	else:
		CloverEnvironment.ENVIRONMENT_TYPE = CloverEnvironmentType.DEVELOPMENT
	if CloverEnvironment.ENVIRONMENT_TYPE == CloverEnvironmentType.RELEASE:
		base_path = Path(sys.executable).parent
		CloverEnvironment.RESOURCES_PATH = base_path / 'resources'
		CloverEnvironment.LOG_PATH = base_path / 'logs'
	else:
		base_path = Path(__file__).parent.parent
		CloverEnvironment.RESOURCES_PATH = base_path / 'resources'
		CloverEnvironment.LOG_PATH = base_path / 'logs'
		str(CloverEnvironment.ENVIRONMENT_TYPE)
	CloverEnvironment.LOG_PATH.mkdir(exist_ok=True)
	CloverEnvironment.RESOURCES_PATH.mkdir(exist_ok=True)


def setup_logger(environment_type):
	log_level_type = {
		CloverEnvironmentType.DEVELOPMENT: logging.DEBUG,
		CloverEnvironmentType.RELEASE: logging.INFO,
	}
	log_level = log_level_type[environment_type]
	formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
	file_handler = logging.FileHandler(CloverEnvironment.LOG_PATH / 'app.log', encoding='utf-8')
	file_handler.setFormatter(formatter)
	file_handler.setLevel(log_level)
	# 配置根日志记录器
	root_logger = logging.getLogger()
	root_logger.setLevel(log_level)
	root_logger.addHandler(file_handler)
	# 控制台处理器（仅开发模式）
	if environment_type == CloverEnvironmentType.DEVELOPMENT:
		console_handler = logging.StreamHandler()
		console_handler.setFormatter(formatter)
		console_handler.setLevel(log_level)
		root_logger.addHandler(console_handler)

	old_excepthook = sys.excepthook

	def handle_exception(exc_type, exc_value, exc_traceback):
		"""处理未捕获的异常"""
		if issubclass(exc_type, KeyboardInterrupt):
			return

		# 记录异常信息
		error_msg = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))
		root_logger.critical(f"未捕获的异常:\n{error_msg}")
		traceback.print_exception(exc_type, exc_value, exc_traceback)
		# 调用原来的异常钩子
		old_excepthook(exc_type, exc_value, exc_traceback)

	sys.excepthook = handle_exception


def win_main():
	setup_environment()
	setup_logger(CloverEnvironment.ENVIRONMENT_TYPE)
	logger = logging.getLogger('Globals')
	logger.info(f"启动环境: {CloverEnvironment.ENVIRONMENT_TYPE}")
	logger.info(f"应用程序目录: {CloverEnvironment.BASE_PATH}")
	logger.info(f"资源目录: {CloverEnvironment.RESOURCES_PATH}")

	try:
		# 创建应用程序实例
		app.start_application(engine)
		# 执行应用程序事件循环
		result = app.exec_()
		logger.info("应用程序已正常退出")
		return result
	except Exception as e:
		logger.critical(f"启动失败: {e}", exc_info=True)
		return -1


def register_repeat_timer(interval, function, *args, **kwargs):
	return engine.register_repeat_timer(interval, function, *args, **kwargs)


def register_delay_exec(interval, function, *args, **kwargs):
	return engine.register_delay_exec(interval, function, *args, **kwargs)


def cancel_timer(timer_id):
	return engine.cancel_timer(timer_id)


if __name__ == '__main__':
	sys.exit(win_main())
